package org.ccay.core.encrypt.impl;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.inject.Inject;
import javax.inject.Named;

import org.apache.commons.codec.binary.Base64;
import org.ccay.core.encrypt.EncryptionException;
import org.ccay.core.encrypt.IEncryption;
import org.ccay.core.util.EncodingUtil;
import org.ccay.core.util.RandomUtil;

/**
 * SHA1 哈希算法，仅支持加密
 * @author chaowangbang
 * @since 2011-11-1
 */
@Named("sha1")
public class Sha1 implements IEncryption {
	/**
	 * 算法名称
	 */
	private static final String SHA_1 = "SHA-1";

	@Inject
	private EncryptConfigBean defaultEncryptConfig;
	
	private static final String EX_HASH_ERROR = "ccay.core.00050003";

	/* （非 Javadoc）
	 * @see org.ccay.core.encrypt.IEncryption#encrypt(java.lang.String, java.lang.String)
	 */
	public String encrypt(String originalString, String key) {
		try {
			MessageDigest md = MessageDigest.getInstance(SHA_1);
			// 此处使用UTF-8编码，避免中文乱码问题
			byte[] bt = (originalString + key).getBytes(EncodingUtil.UTF_8);
			md.update(bt);
			return Base64.encodeBase64String(md.digest());
		} catch (NoSuchAlgorithmException e) {
			throw new EncryptionException(EX_HASH_ERROR, e);
		} catch (UnsupportedEncodingException e) {
			throw new EncryptionException(EX_HASH_ERROR, e);
		}
		
	}

	/* （非 Javadoc）
	 * @see org.ccay.core.encrypt.IEncryption#encrypt(java.lang.String)
	 */
	public String encrypt(String originalString) {
		return encrypt(originalString,defaultEncryptConfig.getDefaultKey());
	}

	/* (non-Javadoc)
	 * @see org.ccay.core.encrypt.IEncryption#generationRandomKey()
	 */
	public String generationRandomKey() {
		return RandomUtil.getRandomString(SHA_1);
	}

	/* (non-Javadoc)
	 * @see org.ccay.core.encrypt.IEncryption#generationRandomKey(int)
	 */
	public String generationRandomKey(int length) {
		return RandomUtil.getRandomString(SHA_1); 
	}

}
